import 'dart:async';
import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:lite_clock/obj/chinese_calendar.dart';
import 'package:lite_clock/util/app_util.dart';
import 'package:lite_clock/util/data_util.dart';
import 'package:lite_clock/util/dio_util.dart';
import 'package:lite_clock/util/storage_util.dart';

///时间管理
class TimeMag {
  DateTime nowTime = DateTime.now();
  ChineseCalendar calendar = ChineseCalendar();

  TimeMag({
    this.nowTime,
    this.calendar,
  });

  TimeMag copyWith({
    DateTime nowTime,
    ChineseCalendar calendar,
  }) =>
      TimeMag(
        nowTime: nowTime ?? this.nowTime,
        calendar: calendar ?? this.calendar,
      );
}

///时间状态管理
class TimeBloc extends Cubit<TimeMag> {
  Timer _timer;

  TimeBloc({TimeMag state})
      : super(TimeMag(nowTime: DateTime.now(), calendar: ChineseCalendar()));

  ///开始计时
  void start() {
    if (_timer == null || !_timer.isActive) {
      _timer = Timer.periodic(const Duration(milliseconds: 500), (_) {
        ///每秒刷新一次
        emit(state.copyWith(nowTime: DateTime.now()));
      });
    }

    LC.log('时钟设置成功');
    getChCalendar();
  }

  ///获取农历
  void getChCalendar() async {
    final bool _shouldGetCh = await StorageUtil.getBool('showC') ?? false;
    if (!_shouldGetCh) {
      ///如果不显示农历
      ///直接拦截
      return;
    }

    LC.log('开始获取农历');

    final Map _chc = json.decode((await StorageUtil.getStr('chc')) ?? '{}');

    //检测本地是否有今天的数据
    //如果没有数据或数据不是今天的
    if (_chc['gregoriandate'] == null ||
        _chc['gregoriandate'].toString().split(' ')[0] !=
            DataUtil.getFormDate(DateTime.now())) {
      LC.log('没有数据');

      final ChineseCalendar _c = await DioUtil.getChCalendar();

      if (_c == null) {
        LC.t('获取农历失败');
        return;
      }

      //保存到本地
      await StorageUtil.setStr('chc', _c.toString());

      emit(state.copyWith(calendar: _c));
    } else {
      //有今天的数据,进行读取
      final ChineseCalendar _c = ChineseCalendar.fromJson(
          json.decode((await StorageUtil.getStr('chc'))));

      emit(state.copyWith(calendar: _c));
    }
  }

  ///结束计时
  void stop() {
    _timer?.cancel();
  }
}
